// pages/messages/messages.js

// 本地工具函数：Promise 化的 wx.request
function wxRequest(options) {
  return new Promise((resolve, reject) => {
    const app = getApp()
    const defaultOptions = {
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }
    }

    // 合并配置
    const requestOptions = {
      ...defaultOptions,
      ...options,
      header: {
        ...defaultOptions.header,
        ...options.header
      }
    }

    // 自动添加 baseUrl
    if (requestOptions.url && !requestOptions.url.startsWith('http')) {
      requestOptions.url = app.globalData.baseUrl + requestOptions.url
    }

    // 自动添加 token
    const token = wx.getStorageSync('token')
    if (token && !requestOptions.header.Authorization) {
      requestOptions.header.Authorization = token
    }

    wx.request({
      ...requestOptions,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// API 简化方法
const api = {
  get(url, data = {}) {
    return wxRequest({ url, method: 'GET', data })
  },
  post(url, data = {}) {
    return wxRequest({ url, method: 'POST', data })
  },
  put(url, data = {}) {
    return wxRequest({ url, method: 'PUT', data })
  },
  delete(url, data = {}) {
    return wxRequest({ url, method: 'DELETE', data })
  }
}

Page({
  data: {
    currentTab: 0,
    tabs: [
      { name: '全部', key: 'all', unread: 0 },
      { name: '劳务', key: 'labor', unread: 0 },
      { name: '订单', key: 'order', unread: 0 },
      { name: '系统', key: 'system', unread: 0 },
      { name: '广播', key: 'broadcast', unread: 0 }
    ],
    messageList: [],
    loading: false,
    loadError: false
  },

  onLoad() {
    this.loadMessages()
  },

  async onShow() {
    // 设置tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      })
    }
    
    await this.loadUnreadStats()
    this.loadMessages()
  },

  onTabChange(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentTab: index
    })
    this.loadMessages()
  },

  async loadMessages() {
    this.setData({ 
      loading: true,
      loadError: false 
    })
    
    try {
      // 获取当前用户ID
      const userInfo = wx.getStorageSync('userInfo')
      if (!userInfo || !userInfo.id) {
        console.error('用户未登录')
        this.setData({ loading: false })
        return
      }

      const currentTab = this.data.tabs[this.data.currentTab].key
      
      // 调用API获取消息列表
      const response = await api.get('/messages', {
        userId: userInfo.id,
        type: currentTab,
        page: 1,
        size: 50
      })

      if (response.data && response.data.code === 200) {
        const messages = response.data.data.records || []
        this.setData({
          messageList: this.formatMessages(messages),
          loading: false
        })
        this.updateUnreadCount()
      } else {
        throw new Error(response.data?.message || '获取消息失败')
      }
    } catch (error) {
      console.error('获取消息失败:', error)
      this.setData({
        messageList: [],
        loading: false,
        loadError: true
      })
    }
  },

  // 重试加载消息
  retryLoadMessages() {
    this.loadMessages()
  },

  // 格式化消息数据
  formatMessages(messages) {
    return messages.map(msg => ({
      id: msg.id,
      type: msg.type || 'system',
      sender: msg.senderName || '系统',
      avatar: msg.senderAvatar || '',
      title: msg.title || '无标题',
      preview: msg.preview || (msg.content ? (msg.content.length > 50 ? msg.content.substring(0, 50) + '...' : msg.content) : ''),
      content: msg.content || '',
      time: this.formatTime(msg.createTime),
      unread: msg.isRead === 0 || msg.isRead === false,
      relatedId: msg.relatedId,
      relatedType: msg.relatedType,
      extraData: msg.extraData,
      priority: msg.priority || 1,
      senderId: msg.senderId || 0,
      receiverId: msg.receiverId
    }))
  },

  formatTime(timeString) {
    if (!timeString) return '未知'
    
    const now = new Date()
    const time = new Date(timeString)
    const diffMs = now - time
    const diffMinutes = Math.floor(diffMs / (1000 * 60))
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
    
    if (diffMinutes < 1) {
      return '刚刚'
    } else if (diffMinutes < 60) {
      return `${diffMinutes}分钟前`
    } else if (diffHours < 24) {
      return `${diffHours}小时前`
    } else if (diffDays < 7) {
      return `${diffDays}天前`
    } else {
      return time.toLocaleDateString()
    }
  },

  onMessageTap(e) {
    const item = e.currentTarget.dataset.item
    
    // 标记为已读
    this.markMessageRead(item.id)
    
    // 根据消息类型跳转不同页面
    switch (item.type) {
      case 'labor':
        this.showLaborMessage(item)
        break
      case 'order':
        this.showOrderMessage(item)
        break
      case 'system':
        this.showSystemMessage(item)
        break
      case 'broadcast':
        this.showBroadcastMessage(item)
        break
      default:
        this.showGeneralMessage(item)
        break
    }
  },

  async markMessageRead(messageId) {
    try {
      const userInfo = wx.getStorageSync('userInfo')
      if (!userInfo || !userInfo.id) {
        console.error('用户未登录')
        return
      }

      // 调用API标记为已读
      await api.put(`/messages/${messageId}/read`, {
        userId: userInfo.id
      })

      // 更新本地状态
      const messageList = this.data.messageList.map(msg => {
        if (msg.id === messageId) {
          return { ...msg, unread: false }
        }
        return msg
      })
      
      this.setData({ messageList })
      this.updateUnreadCount()
    } catch (error) {
      console.error('标记消息已读失败:', error)
    }
  },

  updateUnreadCount() {
    const tabs = this.data.tabs.map(tab => {
      let unreadCount = 0
      
      if (tab.key === 'all') {
        unreadCount = this.data.messageList.filter(msg => msg.unread).length
      } else {
        unreadCount = this.data.messageList.filter(msg => msg.type === tab.key && msg.unread).length
      }
      
      return { ...tab, unread: unreadCount }
    })
    
    this.setData({ tabs })
    
    // 更新 TabBar 的未读消息数量
    const totalUnread = this.data.messageList.filter(msg => msg.unread).length
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().updateUnreadCount(totalUnread)
    }
  },

  showLaborMessage(item) {
    wx.showModal({
      title: item.title || '劳务消息',
      content: item.content || item.preview,
      confirmText: '查看详情',
      cancelText: '稍后处理',
      success: (res) => {
        if (res.confirm && item.relatedId) {
          // 跳转到劳务详情页面
          wx.navigateTo({
            url: `/pages/labor/detail/detail?id=${item.relatedId}`
          })
        }
      }
    })
  },

  showOrderMessage(item) {
    wx.showModal({
      title: item.title || '订单消息',
      content: item.content || item.preview,
      confirmText: '查看详情',
      cancelText: '稍后处理',
      success: (res) => {
        if (res.confirm && item.relatedId) {
          // 跳转到订单详情页面
          wx.navigateTo({
            url: `/pages/orders/detail/detail?id=${item.relatedId}`
          })
        }
      }
    })
  },

  showSystemMessage(item) {
    wx.showModal({
      title: item.title || '系统消息',
      content: item.content || item.preview,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  showBroadcastMessage(item) {
    wx.showModal({
      title: item.title || '广播消息',
      content: item.content || item.preview,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  showGeneralMessage(item) {
    wx.showModal({
      title: item.title || '消息详情',
      content: item.content || item.preview,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  async markAllRead() {
    wx.showModal({
      title: '确认操作',
      content: '确定要将所有消息标记为已读吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const userInfo = wx.getStorageSync('userInfo')
            if (!userInfo || !userInfo.id) {
              console.error('用户未登录')
              return
            }

            const currentTab = this.data.tabs[this.data.currentTab].key
            
            // 调用API标记全部已读
            await api.put('/messages/read-all', {
              userId: userInfo.id,
              type: currentTab
            })

            // 更新本地状态
            const messageList = this.data.messageList.map(msg => ({
              ...msg,
              unread: false
            }))
            
            this.setData({ messageList })
            this.updateUnreadCount()
            
            wx.showToast({
              title: '已全部标记为已读',
              icon: 'success'
            })
          } catch (error) {
            console.error('标记全部已读失败:', error)
            wx.showToast({
              title: '操作失败',
              icon: 'error'
            })
          }
        }
      }
    })
  },

  async clearMessages() {
    wx.showModal({
      title: '确认操作',
      content: '确定要清空所有消息吗？此操作不可恢复。',
      success: async (res) => {
        if (res.confirm) {
          try {
            const userInfo = wx.getStorageSync('userInfo')
            if (!userInfo || !userInfo.id) {
              console.error('用户未登录')
              return
            }

            // 获取当前消息ID列表
            const messageIds = this.data.messageList.map(msg => msg.id)
            
            if (messageIds.length > 0) {
              // 调用API清空消息
              await api.delete('/messages/clear', {
                userId: userInfo.id,
                type: this.data.tabs[this.data.currentTab].key
              })
            }

            // 更新本地状态
            this.setData({
              messageList: [],
              tabs: this.data.tabs.map(tab => ({ ...tab, unread: 0 }))
            })
            
            // 更新 TabBar 的未读消息数量
            if (typeof this.getTabBar === 'function' && this.getTabBar()) {
              this.getTabBar().updateUnreadCount(0)
            }
            
            wx.showToast({
              title: '消息已清空',
              icon: 'success'
            })
          } catch (error) {
            console.error('清空消息失败:', error)
            wx.showToast({
              title: '操作失败',
              icon: 'error'
            })
          }
        }
      }
    })
  },

  // 加载未读消息统计
  async loadUnreadStats() {
    try {
      const userInfo = wx.getStorageSync('userInfo')
      if (!userInfo || !userInfo.id) {
        return
      }

      const response = await api.get('/messages/unread-stats', {
        userId: userInfo.id
      })

      if (response.data.code === 200) {
        const stats = response.data.data
        const tabs = this.data.tabs.map(tab => ({
          ...tab,
          unread: stats[tab.key] || 0
        }))
        this.setData({ tabs })
      }
    } catch (error) {
      console.error('获取未读消息统计失败:', error)
    }
  }
})